package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


/**
 * @author lifeihu
 * @date 2021/12/29
 * @TIME:19:41
 */
@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveFriend(Long userId, Long friendId) {
        //1.当前用户-》好友--存储
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
       /* Friend friend = mongoTemplate.findOne(query, Friend.class);*/
        if(!mongoTemplate.exists(query1, Friend.class)){
            Friend friend=new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            mongoTemplate.save(friend);
        }
        //2.好友-》当前用户--存储
        //2、保存好友的数据
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("frinedId").is(userId));
        //2.1 判断好友关系是否存在
        if (!mongoTemplate.exists(query2, Friend.class)) {
            //2.2 如果不存在，保存
            Friend friend1 = new Friend();
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
    }

    @Override
    public List<Friend> findFriends(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list;
    }
}
